﻿SSVC.Utils.Page.IncludeFile("../styles/FilterPopup.css", "css");

SSVC.Wrap.Dojo.Require([
    "dojo/_base/fx",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/mouse",
    "dojo/on",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dojo/text!../scripts/FilterPopup.html"],

	function(baseFx, lang, domStyle, mouse, on, _WidgetBase, _TemplatedMixin, template)
	{
		function filterPopupLogic(filterPopupWidgetPar)
		{
			var fpWidget = filterPopupWidgetPar;

			var self = this;

			var cmbMessageType, cmbTimeFrame, cmbDateUnits;

			var filteringMessage;

			this.onChangeTimeFrame = function()
			{
				var value = cmbTimeFrame.GetValue();
				if (value == SSVC.Utils.GetResource("fp_all"))
				{
					fpWidget.TimeframeLastNode.style.display = "none";
					fpWidget.TimeframeRangeNode.style.display = "none";
				}
				if (value == SSVC.Utils.GetResource("fp_last_x_times"))
				{
					fpWidget.TimeframeLastNode.style.display = "block";
					fpWidget.TimeframeRangeNode.style.display = "none";
				}
				if (value == SSVC.Utils.GetResource("fp_date_range"))
				{
					fpWidget.TimeframeLastNode.style.display = "none";
					fpWidget.TimeframeRangeNode.style.display = "block";
				}
			};

			this.onClickGenerationDoRange = function()
			{
				fpWidget.GenerationDefaultNode.style.display = "none";
				fpWidget.GenerationRangeNode.style.display = "inline";
			};

			this.onClickGenerationCancel = function()
			{
				fpWidget.GenerationDefaultNode.style.display = "inline";
				fpWidget.GenerationRangeNode.style.display = "none";
			};

			this.onClickCalendarShow = function(btn)
			{
				var param = { aras: top.aras, format: top.aras.getDotNetDatePattern("short_date") };
				var res = top.aras.uiShowDialogNearElement(btn, top.aras.getScriptsURL() + "dateDialog.html", param);

				if (SSVC.Utils.isNullOrUndefined(res))
					res = "";

				if (btn.id == "btnDStartCalendarShow")
					fpWidget.edtDateStartNode.value = res;

				if (btn.id == "btnDFinishCalendarShow")
					fpWidget.edtDateFinishNode.value = res;
			};

			this.onFocusInput = function(elem)
			{
				if (elem.id == "edtFromUserName" && elem.value == SSVC.Utils.GetResource("fp_anyone"))
				{
					elem.value = "";
					SSVC.Wrap.Dojo.RemoveClass(elem.id, "fpGrayedText");
				}
				else
					if (elem.value == SSVC.Utils.GetResource("fp_all"))
					{
						elem.value = "";
						SSVC.Wrap.Dojo.RemoveClass(elem.id, "fpGrayedText");
					}
			};

			this.onBlurInput = function(elem)
			{
				if (elem.value.trim() == "")
				{
					if (elem.id == "edtFromUserName")
						elem.value = SSVC.Utils.GetResource("fp_anyone");
					else
						elem.value = SSVC.Utils.GetResource("fp_all");
					SSVC.Wrap.Dojo.AddClass(elem.id, "fpGrayedText");
				}
			};

			this.Load = function()
			{
				var itms = top.aras.newIOMItem("VC_FeedFilterType");
				var aml =
					"<AML>" +
						"<Item type=\"VC_CommonSettings\" action=\"get\" select=\"id\">" +
							"<Relationships>" +
								"<Item type=\"VC_CommonSettingsFilterType\" select=\"id,related_id(id)\">" +
									"<related_id>" +
										"<Item action=\"get\" type=\"VC_FeedFilterType\">" +
											"<enabled>1</enabled>" +
										"</Item>" +
									"</related_id>" +
								"</Item>" +
							"</Relationships>" +
						"</Item>" +
					"</AML>";
				itms.loadAML(aml);
				itms = itms.apply();
				itms = itms.getItemsByXPath("Relationships/Item/related_id/Item");

				var messageTypes = [];

				var idsString = "";
				for (var i = 0; i < itms.getItemCount() ; i++)
					idsString += itms.getItemByIndex(i).getID() + ",";
				if (idsString.length > 0)
				{
					idsString = idsString.substr(0, idsString.length - 1);
					aml =
						"<AML>" +
							"<Item action='get' type='VC_FeedFilterType' orderBy='filter_sort_order' select='filter_name, filter_classification'>" +
								"<id condition=\"in\">" + idsString + "</id>" +
							"</Item>" +
						"</AML>";
					itms.loadAML(aml);
					itms = itms.apply();
				}

				for (var i = 0; i < itms.getItemCount() ; i++)
					messageTypes.push({ label: itms.getItemByIndex(i).getProperty("filter_name"), value: itms.getItemByIndex(i).getProperty("filter_classification") });

				cmbMessageType = new SSVC.Wrap.Dojo.Form.Select();
				cmbMessageType.Load(
					{
						id: "cmbMessageTypeInner",
						style: { width: "117px", height: "20px", float: "left", background: "white", border: "1px solid #6B6B6B", font: "13px Tahoma, Arial, Helvetica, sans-serif" },
						options: messageTypes
					});
				cmbMessageType.PlaceAt(fpWidget.cmbMessageTypeNode);

				cmbTimeFrame = new SSVC.Wrap.Dojo.Form.Select();
				cmbTimeFrame.Load(
					{
						id: "cmbTimeFrameInner",
						style: { width: "117px", height: "20px", float: "left", background: "white", border: "1px solid #6B6B6B", font: "13px Tahoma, Arial, Helvetica, sans-serif" },
						options: [
							{ label: SSVC.Utils.GetResource("fp_all"), value: SSVC.Utils.GetResource("fp_all"), selected: true },
							{ label: SSVC.Utils.GetResource("fp_last_x_times"), value: SSVC.Utils.GetResource("fp_last_x_times") },
							{ label: SSVC.Utils.GetResource("fp_date_range"), value: SSVC.Utils.GetResource("fp_date_range") }
						]
					});
				cmbTimeFrame.On("change", function() { self.onChangeTimeFrame(cmbTimeFrame); });
				cmbTimeFrame.PlaceAt(fpWidget.cmbTimeFrameNode);

				cmbDateUnits = new SSVC.Wrap.Dojo.Form.Select();
				cmbDateUnits.Load(
					{
						id: "cmbDateUnitsInner",
						style: { width: "67px", height: "20px", float: "left", background: "white", border: "1px solid #6B6B6B", font: "13px Tahoma, Arial, Helvetica, sans-serif" },
						options: [
							{ label: SSVC.Utils.GetResource("fp_minutes"), value: SSVC.Utils.GetResource("fp_minutes") },
							{ label: SSVC.Utils.GetResource("fp_hours"), value: SSVC.Utils.GetResource("fp_hours") },
							{ label: SSVC.Utils.GetResource("fp_days"), value: SSVC.Utils.GetResource("fp_days"), selected: true },
							{ label: SSVC.Utils.GetResource("fp_months"), value: SSVC.Utils.GetResource("fp_months") },
						]
					});
				cmbDateUnits.PlaceAt(fpWidget.cmbDateUnitsNode);
			};

			this.SubscribeEvents = function()
			{
				fpWidget.edtFromUserNameNode.addEventListener("focus", SSVC.Wrap.Dojo.Partial(self.onFocusInput, fpWidget.edtFromUserNameNode));
				fpWidget.edtFromUserNameNode.addEventListener("blur", SSVC.Wrap.Dojo.Partial(self.onBlurInput, fpWidget.edtFromUserNameNode));

				fpWidget.btnDStartCalendarShowNode.addEventListener("click", SSVC.Wrap.Dojo.Partial(self.onClickCalendarShow, fpWidget.btnDStartCalendarShowNode));

				fpWidget.btnDFinishCalendarShowNode.addEventListener("click", SSVC.Wrap.Dojo.Partial(self.onClickCalendarShow, fpWidget.btnDFinishCalendarShowNode));

				fpWidget.edtRevisionNode.addEventListener("focus", SSVC.Wrap.Dojo.Partial(self.onFocusInput, fpWidget.edtRevisionNode));
				fpWidget.edtRevisionNode.addEventListener("blur", SSVC.Wrap.Dojo.Partial(self.onBlurInput, fpWidget.edtRevisionNode));

				fpWidget.edtGenerationNode.addEventListener("focus", SSVC.Wrap.Dojo.Partial(self.onFocusInput, fpWidget.edtGenerationNode));
				fpWidget.edtGenerationNode.addEventListener("blur", SSVC.Wrap.Dojo.Partial(self.onBlurInput, fpWidget.edtGenerationNode));

				fpWidget.GenerationDefaultNode.addEventListener("click", self.onClickGenerationDoRange);

				fpWidget.btnGenerationCancelNode.addEventListener("click", self.onClickGenerationCancel);

				fpWidget.edtStateNode.addEventListener("focus", SSVC.Wrap.Dojo.Partial(self.onFocusInput, fpWidget.edtStateNode));
				fpWidget.edtStateNode.addEventListener("blur", SSVC.Wrap.Dojo.Partial(self.onBlurInput, fpWidget.edtStateNode));
			}

			this.Validate = function()
			{
				var validationErrors = [];

				if (fpWidget.TimeframeLastNode.style.display != "none")
				{
					if (!isPositiveInteger(fpWidget.edtDateCountNode.value))
						validationErrors.push("{0} {1}".Format(SSVC.Utils.GetResource("fp_incorrect_x_times"), cmbDateUnits.GetValue()));
				}

				if (fpWidget.TimeframeRangeNode.style.display != "none")
				{
					if (fpWidget.edtDateStartNode.value.trim() == "")
						validationErrors.push(SSVC.Utils.GetResource("fp_val_no_start_date"));
					if (fpWidget.edtDateFinishNode.value.trim() == "")
						validationErrors.push(SSVC.Utils.GetResource("fp_val_no_finish_date"));
				}

				if (fpWidget.GenerationDefaultNode.style.display != "none")
				{
					if (fpWidget.edtGenerationNode.value != "All" && !isPositiveInteger(fpWidget.edtGenerationNode.value))
						validationErrors.push(SSVC.Utils.GetResource("fp_val_incorrect_generation"));
				}

				if (fpWidget.GenerationRangeNode.style.display != "none")
				{
					if (!isPositiveInteger(fpWidget.edtGenerationNode.value))
						validationErrors.push(SSVC.Utils.GetResource("fp_val_incorrect_generation_start"));

					if (!isPositiveInteger(fpWidget.edtGenerationEndNode.value))
						validationErrors.push(SSVC.Utils.GetResource("fp_val_incorrect_generation_finish"));
				}

				if (validationErrors.length > 0)
				{
					var errorsHtml = "";
					for (var i = 0; i < validationErrors.length; i++)
						errorsHtml += validationErrors[i] + "<br />";

					fpWidget.divValidationErrorsNode.innerHTML = errorsHtml;
					fpWidget.divValidationErrorsNode.style.display = "inline";
					return false;
				}
				else
				{
					fpWidget.divValidationErrorsNode.style.display = "none";
					fpWidget.divValidationErrorsNode.innerHTML = "";
					return true;
				}
			};

			this.ComposeFilterArray = function()
			{
				var filterArr = [];
				filteringMessage = "";

				if (fpWidget.edtFromUserNameNode.value != SSVC.Utils.GetResource("fp_anyone"))
				{
					filterArr.push(
						{
							name: "name",
							text: "*" + fpWidget.edtFromUserNameNode.value + "*",
							condition: "like",
							itemProperty: "from_identity"
						});
					filteringMessage += "{0} \"{1}\",".Format(SSVC.Utils.GetResource("fp_from").toLowerCase(), fpWidget.edtFromUserNameNode.value);
				}

				var selectedLabel;
				var messageTypeOptions = cmbMessageType.GetOptions();
				for (var i = 0; i < messageTypeOptions.length; i++)
					if (messageTypeOptions[i].selected)
					{
						selectedLabel = messageTypeOptions[i].label;
						break;
					}

				if (selectedLabel != SSVC.Utils.GetResource("fp_all"))
				{
					filterArr.push(
						{
							name: "classification",
							text: cmbMessageType.GetValue()
						});
					filteringMessage += "{0} {1},".Format(SSVC.Utils.GetResource("fp_type").toLowerCase(), selectedLabel);
				}

				if (cmbTimeFrame.GetValue() == SSVC.Utils.GetResource("fp_last_x_times"))
				{
					var startDate = new Date();
					switch (cmbDateUnits.GetValue())
					{
						case SSVC.Utils.GetResource("fp_minutes"):
							startDate.setMinutes(startDate.getMonth() - fpWidget.edtDateCountNode.value);
							break;
						case SSVC.Utils.GetResource("fp_hours"):
							startDate.setHours(startDate.getHours() - fpWidget.edtDateCountNode.value);
							break;
						case SSVC.Utils.GetResource("fp_days"):
							startDate.setDate(startDate.getDate() - fpWidget.edtDateCountNode.value);
							break;
						case SSVC.Utils.GetResource("fp_months"):
							startDate.setMonth(startDate.getMonth() - fpWidget.edtDateCountNode.value);
							break;
					}

					filterArr.push(
						{
							name: "sent",
							text: SSVC.Utils.GetDateTimeInNeutralFormat(startDate),
							condition: "ge"
						});
					filteringMessage += "{0} {1} {2},".Format(SSVC.Utils.GetResource("fp_last"), fpWidget.edtDateCountNode.value, cmbDateUnits.GetValue().toLowerCase());
				}

				if (cmbTimeFrame.GetValue() == SSVC.Utils.GetResource("fp_date_range"))
				{
					var startDate = new Date(fpWidget.edtDateStartNode.value);
					var finishDate = new Date(fpWidget.edtDateFinishNode.value);

					filterArr.push(
						{
							name: "sent",
							text: SSVC.Utils.GetDateTimeInNeutralFormat(startDate),
							condition: "ge"
						});
					filterArr.push(
						{
							name: "sent",
							text: SSVC.Utils.GetDateTimeInNeutralFormat(finishDate),
							condition: "le"
						});
					filteringMessage += "{0} {1} {2},".Format(fpWidget.edtDateStartNode.value, SSVC.Utils.GetResource("fp_to"), fpWidget.edtDateFinishNode.value);
				}

				if (fpWidget.edtRevisionNode.value != SSVC.Utils.GetResource("fp_all"))
				{
					filterArr.push(
					{
						name: "major_rev",
						text: edtRevision.value
					});
					filteringMessage += "{0} {1},".Format(SSVC.Utils.GetResource("fp_revision").toLowerCase(), fpWidget.edtRevisionNode.value);
				}

				if (fpWidget.edtGenerationNode.value != SSVC.Utils.GetResource("fp_all"))
				{
					if (fpWidget.GenerationRangeNode.style.display != "none")
					{
						filterArr.push(
						{
							name: "generation",
							text: fpWidget.edtGenerationNode.value,
							condition: "ge"
						});
						filterArr.push(
						{
							name: "generation",
							text: fpWidget.edtGenerationEndNode.value,
							condition: "le"
						});
						filteringMessage += "{0} {1} {2} {3},".Format(SSVC.Utils.GetResource("fp_generation").toLowerCase(), fpWidget.edtGenerationNode.value, SSVC.Utils.GetResource("fp_to"), fpWidget.edtGenerationEndNode.value);
					}
					else
					{
						filterArr.push(
						{
							name: "generation",
							text: fpWidget.edtGenerationNode.value
						});
						filteringMessage += "{0} {1},".Format(SSVC.Utils.GetResource("fp_generation").toLowerCase(), fpWidget.edtGenerationNode.value);
					}
				}

				if (fpWidget.edtStateNode.value != SSVC.Utils.GetResource("fp_all"))
				{
					filterArr.push(
						{
							name: "state",
							text: fpWidget.edtStateNode.value
						});
					filteringMessage += "{0} \"{1}\",".Format(SSVC.Utils.GetResource("fp_state").toLowerCase(), fpWidget.edtStateNode.value);
				}

				if (filteringMessage.length > 0)
					filteringMessage = filteringMessage.substr(0, filteringMessage.length - 1);

				return filterArr;
			};

			this.ResetFields = function()
			{
				cmbMessageType.SetSelectedOption(0);
				fpWidget.edtFromUserNameNode.value = "";
				self.onBlurInput(fpWidget.edtFromUserNameNode);

				cmbTimeFrame.SetSelectedOption(0);
				cmbDateUnits.SetSelectedOption(2);
				fpWidget.edtDateStartNode.value = "";
				fpWidget.edtDateFinishNode.value = "";
				fpWidget.edtRevisionNode.value = "";
				self.onBlurInput(fpWidget.edtRevisionNode);

				fpWidget.edtGenerationNode.value = "";
				self.onBlurInput(fpWidget.edtGenerationNode);

				fpWidget.GenerationRangeNode.style.display = "none";
				fpWidget.edtGenerationEndNode.value = "";
				fpWidget.edtStateNode.value = "";
				self.onBlurInput(fpWidget.edtStateNode);
			};

			this.GetFilteringMessage = function()
			{
				return filteringMessage;
			};

			function isPositiveInteger(cand)
			{
				var n = ~~Number(cand);
				return String(n) === cand && n > 0;
			};
		}

		return SSVC.Wrap.Dojo.SetObject("SSVC.UI.FilterPopup", SSVC.Wrap.Dojo.Declare([_WidgetBase, _TemplatedMixin],
			{
				templateString: template,

				TypeLabel: SSVC.Utils.GetResource("fp_type"),
				FromLabel: SSVC.Utils.GetResource("fp_from"),
				FromDefValue: SSVC.Utils.GetResource("fp_anyone"),
				TimeframeLabel: SSVC.Utils.GetResource("fp_timeframe"),
				ToLabel: SSVC.Utils.GetResource("fp_to"),
				RevisionLabel: SSVC.Utils.GetResource("fp_revision"),
				RevisionDefValue: SSVC.Utils.GetResource("fp_all"),
				GenerationLabel: SSVC.Utils.GetResource("fp_generation"),
				GenerationDefValue: SSVC.Utils.GetResource("fp_all"),
				RangeLabel: SSVC.Utils.GetResource("fp_range_indicator"),
				StateLabel: SSVC.Utils.GetResource("fp_state"),
				StateDefValue: SSVC.Utils.GetResource("fp_all"),
				SearchButtonLabel: SSVC.Utils.GetResource("fp_search"),
				CancelButtonLabel: SSVC.Utils.GetResource("fp_cancel"),

				fpl: null,

				constructor: function()
				{
					this.fpl = new filterPopupLogic(this);
				},

				postCreate: function()
				{
					this.fpl.Load();
					this.fpl.SubscribeEvents();

					this.own(
						on(this.btnSearchNode, "click", lang.hitch(this, "btnSearchNode_OnClick")),
						on(this.btnCancelNode, "click", lang.hitch(this, "btnCancelNode_OnClick")));
				},

				ComposeFilterArray: function()
				{
					return this.fpl.ComposeFilterArray();
				},

				Validate: function()
				{
					return this.fpl.Validate();
				},

				GetFilteringMessage: function()
				{
					return this.fpl.GetFilteringMessage();
				},

				ResetFields: function()
				{
					return this.fpl.ResetFields();
				},

				OnBtnSearchNodeClick: function() { },
				OnBtnCancelNodeClick: function() { },

				btnSearchNode_OnClick: function()
				{
					this.OnBtnSearchNodeClick(arguments, this);
				},
				btnCancelNode_OnClick: function()
				{
					this.OnBtnCancelNodeClick(arguments, this);
				}
			}));
	});